package name.fuhan.shipin;

import java.io.Serializable;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import android.widget.VideoView;

import com.lidroid.xutils.BitmapUtils;

public class ShiPinView extends RelativeLayout implements OnClickListener,
		Serializable, OnSeekBarChangeListener {

	protected VideoView video;
	protected ImageView iv;
	protected ImageButton ib;
	protected SeekBar pb;
	protected static Drawable button_gz_shape;
	protected static BitmapUtils bmUtils;
	protected int position;
	protected Drawable wunai;
	protected RotateAnimation rotateAnimation;

	public static class Config{
		public static void setBitmapUtils(BitmapUtils bitmapUtils) {
			ShiPinView.bmUtils = bitmapUtils;
		}
	}
	
	public ShiPinView(Context context, AttributeSet attrs) {
		super(context, attrs);
		if (bmUtils == null)
			bmUtils = new BitmapUtils(context);
		button_gz_shape = getContext().getApplicationContext().getResources()
				.getDrawable(R.drawable.icon_post_copyright);
		View inflate = LayoutInflater.from(context).inflate(
				R.layout.shi_pin_view, null);
		video = (VideoView) inflate.findViewById(R.id.shipin_video);
		iv = (ImageView) inflate.findViewById(R.id.shipin_iv);
		ib = (ImageButton) inflate.findViewById(R.id.shipin_ib);
		pb = (SeekBar) inflate.findViewById(R.id.shipin_pb);
		addView(inflate);
	}

	public ShiPinView(Context context) {
		super(context);
		if (bmUtils == null)
			bmUtils = new BitmapUtils(context);
		View inflate = LayoutInflater.from(context).inflate(
				R.layout.shi_pin_view, null);
		video = (VideoView) inflate.findViewById(R.id.shipin_video);
		iv = (ImageView) inflate.findViewById(R.id.shipin_iv);
		ib = (ImageButton) inflate.findViewById(R.id.shipin_ib);
		pb = (SeekBar) inflate.findViewById(R.id.shipin_pb);
		addView(inflate);
	}


	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		wunai = getContext().getResources().getDrawable(R.drawable.wunai);

		pb.setOnSeekBarChangeListener(this);
		ib.setOnClickListener(this);

		setOnClickListener(this);

		rotateAnimation = new RotateAnimation(0, 360,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		rotateAnimation.setDuration(500);
		rotateAnimation.setRepeatCount(Integer.MAX_VALUE);
		rotateAnimation.setInterpolator(new LinearInterpolator());// 匀速

	}

	boolean 第一次 = true;
	protected ListView listView;
	protected String imageAddress;
	protected String videoAddress;

	public ShiPinView setAddress(String imageAddress, String videoAddress,
			ListView listView, int measuredWidth, int measuredHeight,
			int position) {
		this.imageAddress = imageAddress;
		this.videoAddress = videoAddress;
		this.listView = listView;
		this.position = position;
		Log.d("TGAV", videoAddress);
		重置();
		ib.setTag(videoAddress);
		调整大小(measuredWidth, measuredHeight);
		加载首帧图片(imageAddress);
		return this;
	}

	protected void 加载首帧图片(String imageAddress) {
		bmUtils.display(iv, imageAddress);
	}

	protected void 调整大小(int measuredWidth, int measuredHeight) {
		WindowManager wm = (WindowManager) getContext().getSystemService(
				Context.WINDOW_SERVICE);

		int windowWidth = wm.getDefaultDisplay().getWidth();
		int windowHeight = wm.getDefaultDisplay().getHeight();
		Log.d("TGAV", "得到屏幕的宽度为" + windowWidth);

		int width3 = measuredWidth;
		int height3 = measuredHeight;

		int width = windowWidth;
		int height = height3 * windowWidth / width3;
		Log.d("TGAV", "计算后图片的高度" + height);
		setMeasuredDimension(width, height);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,
				height);
		setLayoutParams(params);
	}

	protected void 加载视频(String videoAddress) {
		video.setVideoURI(Uri.parse(videoAddress));
		// 让VideiView获取焦点
		video.requestFocus();

		video.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {

				setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				ShiPinView.this.postInvalidate();
				video.measure(mp.getVideoWidth(), mp.getVideoHeight());
				video.postInvalidate();
				Log.i("TGAV", "视频准备好了");

				ib.clearAnimation();
				ib.setBackgroundResource(R.drawable.play_bt_selector);

				第一次 = false;
				iv.setVisibility(View.GONE);
				ib.setVisibility(View.GONE);

				pb.setMax(video.getDuration());
				video.start();
				Log.d("TGAV", "开始播放");
				handler.sendEmptyMessage(0);

			}
		});
		video.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				Log.i("TGAV", "视频播放完了");
				video.seekTo(0);
				video.pause();
				pb.setProgress(0);
				handler.removeCallbacksAndMessages(null);
			}
		});
		video.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				handler.removeCallbacksAndMessages(null);
				// ib.setClickable(false);
				iv.setVisibility(View.VISIBLE);
				android.view.ViewGroup.LayoutParams layoutParams = iv
						.getLayoutParams();
				int w = layoutParams.width;
				int h = layoutParams.height;
				iv.setImageDrawable(wunai);
				iv.setLayoutParams(new LayoutParams(w, h));
				video.setVisibility(View.GONE);
				Toast.makeText(getContext(), "你的设备无法播放视频...", 0).show();
				return true;
			}
		});

		ib.setBackgroundResource(R.drawable.progress_bar_icon);
		ib.startAnimation(rotateAnimation);

	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		measureChildren(widthMeasureSpec, heightMeasureSpec);
	}

	public void 重置() {
		Log.w("TGAV", "重置了");
		handler.removeCallbacksAndMessages(null);
		第一次 = true;
		ib.setClickable(false);
		position = -1;
		iv.setImageDrawable(button_gz_shape);
		iv.setVisibility(View.VISIBLE);
		try {
			if (video != null) {
				video.stopPlayback();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		ib.clearAnimation();
		ib.setBackgroundResource(R.drawable.play_bt_selector);

		ib.setVisibility(View.VISIBLE);
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			handler.removeCallbacksAndMessages(null);

			int curr = video.getCurrentPosition();
			pb.setProgress(curr);
			Log.d("TGAV", "当前进度" + curr);

			if (listView != null && position != -1) {
				int firstVisiblePosition = listView.getFirstVisiblePosition();
				int lastVisiblePosition = listView.getLastVisiblePosition();
				if (position < firstVisiblePosition
						|| position > lastVisiblePosition) {
					暂停();
					return;
				}
			}
			handler.sendEmptyMessageDelayed(0, 1000);
		}
	};

	long lastTime;

	@Override
	public void onClick(View v) {
		long time = System.currentTimeMillis();
		if (time - lastTime < 1500) {// 在1.5秒内双击
			切换横竖屏();
		}
		lastTime = time;
		if (第一次 && !video.isPlaying()) {
			Log.d("TGAV", "第一次点击");
			String videoAddress = (String) ib.getTag();
			加载视频(videoAddress);
			return;
		}

		// TODO 点画面暂停
		if (video.isPlaying()) {// 正在播放中
			暂停();
		} else {
			恢复();
		}

	}

	public boolean 当前横屏;

	protected void 切换横竖屏() {
		if (当前横屏) {
			return;
		}
		Intent intent = new Intent(getContext(), ShowShiPinActivity.class);
		intent.putExtra("videoAddress", videoAddress);
		intent.putExtra("imageAddress", imageAddress);
		if (video.isPlaying()) {
			暂停();
			intent.putExtra("jindu", 播放进度);
		}
		getContext().startActivity(intent);
	}

	protected int 播放进度;

	public void 暂停() {
		if (video.isPlaying()) {// 正在播放中
			Log.i("TGAV", "暂停了");
			播放进度 = video.getCurrentPosition();
			video.pause();
			// video.suspend()
			ib.setVisibility(View.VISIBLE);
			handler.removeCallbacksAndMessages(null);
		}
	}

	public void 恢复() {
		if (!video.isPlaying()) {// 正在播放中
			Log.i("TGAV", "恢复了");
			video.seekTo(播放进度);
			video.start();
			ib.setVisibility(View.GONE);
			handler.sendEmptyMessage(0);
		}
	}

	@Override
	protected void onDetachedFromWindow() {
		handler.removeCallbacksAndMessages(null);
		try {
			if (video != null) {
				video.stopPlayback();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDetachedFromWindow();
	}

	// 拖拽
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		if (fromUser)
			播放进度 = progress;
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		暂停();
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		恢复();
	}

}
